import React, { createRef } from 'react';

// 自己写的双向绑定
export default class extends React.Component {

  // 官方提供的
  state = {
    list: [],
    showingList: [],
    editingId: null,
    editingValue: '',
  };

  inp = createRef(null);
  editInp = createRef(null);

  // 自己写的
  onAdd () {
    const newList = this.state.list.concat({
      id: Date.now(),
      value: this.inp.current.value,
    });
    this.setState({
      list: newList,
      showingList: newList.concat(),
    });
  }

  // 自己写的
  onDelete (id) {
    const newList = this.state.list.filter(item => item.id !== id);
    this.setState({
      list: newList,
      showingList: newList.concat(),
    });
  }

  // 数组方法中 操作原数组的
  // push shift unshift pop splice reverse sort

  onEdit (item) {
    this.setState({
      editingId: item.id,
      editingValue: item.value,
    });
  }

  onEditOk (id) {
    const newList = this.state.list.map(item => ({
      ...item,
      value: item.id === id ? this.state.editingValue : item.value,
    }));
    this.setState({
      list: newList,
      showingList: newList.concat(),
      editingId: null,
    });
  }

  onEditingInpChange (e) {
    this.setState({
      editingValue: e.target.value,
    });
  }

  createListItem (item) {
    if (item.id === this.state.editingId) {
      return (
        <>
          <input
            type="text"
            value={ this.state.editingValue }
            onChange={ this.onEditingInpChange.bind(this) }
          />
          <button onClick={ this.onEditOk.bind(this, item.id) }>ok</button>
        </>
      );
    } else {
      return (
        <>
          { item.value }
          <button onClick={ this.onEdit.bind(this, item) }>修改</button>
        </>
      );
    }
  }

  // 自己写的
  // 数组项小模块
  createList () {
    return this.state.showingList.map((item) => (
      <li key={ item.id }>
        { this.createListItem(item) }
        {/* <button onClick={ () => this.onDelete.call(this, item.id) }>删除</button> */}
        <button onClick={ this.onDelete.bind(this, item.id) }>删除</button>
      </li>
    ));
  }

  // 自己写的
  onSearch () {
    this.setState({
      showingList: this.state.list.filter(item => item.value.includes(this.inp.current.value)),
    });
  }

  // 官方的
  render () {
    return (
      <>
        <input
          type="text"
          ref={ this.inp }
        />
        <button onClick={ this.onAdd.bind(this) }>新增</button>
        <button onClick={ this.onSearch.bind(this) }>查询</button>
        <ul>{ this.createList() }</ul>
      </>
    );
  }

}
